package com.gw.booking.common;

import org.apache.commons.lang.StringUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;


public class SimpleMailSender {
	/**   
     * 以HTML格式发送邮件   
     * @param toAddress 接收邮件地址   
     * @param title 邮件标题 
     * @param content 邮件内容
     * @param filePath 不为空时作为附件发送
     */    
   public static boolean sendHtmlMail(String toAddress, String title, String content, String filePath){    
       List<String> toAddresses = new ArrayList<String>();
       toAddresses.add(toAddress);
       
       return sendHtmlMail(toAddresses, title, content, filePath);
   }
   
    /**   
      * 以HTML格式发送邮件   
      * @param toAddresses 接收邮件地址 列表 
      * @param title 邮件标题 
      * @param content 邮件内容
      * @param filePath 不为空时作为附件发送
      */    
    public static boolean sendHtmlMail(List<String> toAddresses, String title, String content, String filePath){
        return sendHtmlMail(toAddresses, null, title, content, filePath);
    } 
     
  /**   
    * 以HTML格式发送邮件   
    * @param recipients 接收邮件地址 列表
    * @param ccAddresses 抄送邮件地址 列表 
    * @param title 邮件标题 
    * @param content 邮件内容
    * @param filePath 不为空时作为附件发送
    */    
  public static boolean sendHtmlMail(List<String> recipients, List<String> ccAddresses, String title, String content, String filePath){    
		MailSenderInfo mailInfo = new MailSenderInfo();  
		mailInfo.setValidate(true);

		//正式邮箱(ali)
		mailInfo.setMailServerPort("25");   
		mailInfo.setMailServerHost("smtp.aliyun.com");
		mailInfo.setUserName("runzhen@aliyun.com");
		mailInfo.setPassword("lajaylar830922");//您的邮箱密码
		mailInfo.setFromAddress("runzhen@aliyun.com");

		mailInfo.setContent(content);
		mailInfo.setSubject(title);
		
		//判断是否需要身份认证
		MyAuthenticator authenticator = null;   
		Properties pro = mailInfo.getProperties();
		
		

		//如果需要身份认证，则创建一个密码验证器     
		if (mailInfo.isValidate()) {    
			authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());   
		}
		// 根据邮件会话属性和密码验证器构造一个发送邮件的session    
		Session sendMailSession = Session.getDefaultInstance(pro,authenticator);    
		List<String> toAddresses = new ArrayList<String>();
		try {    
			// 根据session创建一个邮件消息    
			Message mailMessage = new MimeMessage(sendMailSession);    
			// 创建邮件发送者地址    
			Address from = new InternetAddress(mailInfo.getFromAddress());    
			// 设置邮件消息的发送者    
			mailMessage.setFrom(from);    
			// 创建邮件的接收者地址，并设置到邮件消息中    
			for (String address : recipients) {
				if (Pattern.matches("[^@]+@[^@]+", address)) {
					toAddresses.add(address);
				}
			}
			Address[] tos = new InternetAddress[toAddresses.size()];
			for (int i = 0; i < toAddresses.size(); i++) {
				tos[i] = new InternetAddress(toAddresses.get(i));
			}
			// Message.RecipientType.TO属性表示接收者的类型为TO    
			mailMessage.setRecipients(Message.RecipientType.TO, tos);  

			//添加抄送地址
			if (ccAddresses != null && ccAddresses.size() > 0) {
				// 创建邮件的接收者地址，并设置到邮件消息中    
				for (String address : ccAddresses) {
					if (!Pattern.matches("[^@]+@[^@]+", address)) {
						ccAddresses.remove(address);
					}
				}
				Address[] ccs = new InternetAddress[ccAddresses.size()];
				for (int i = 0; i < ccAddresses.size(); i++) {
					ccs[i] = new InternetAddress(ccAddresses.get(i));
				}
				// Message.RecipientType.CC属性表示接收者的类型为CC    
				mailMessage.setRecipients(Message.RecipientType.CC, ccs);  
			}

			// 设置邮件消息的主题    
			mailMessage.setSubject(mailInfo.getSubject());    
			// 设置邮件消息发送的时间    
			mailMessage.setSentDate(new Date());    
			// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象    
			Multipart mainPart = new MimeMultipart();    
			// 创建一个包含HTML内容的MimeBodyPart    
			BodyPart html = new MimeBodyPart();    
			// 设置HTML内容    
			html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");    
			mainPart.addBodyPart(html);   

			//添加附件
			if (StringUtils.isNotEmpty(filePath)) {
				BodyPart attach = new MimeBodyPart();  
				FileDataSource fds = new FileDataSource(filePath);
				attach.setFileName(fds.getName());
				attach.setDataHandler(new DataHandler(fds));

				mainPart.addBodyPart(attach);
			}

			// 将MiniMultipart对象设置为邮件内容
			mailMessage.setContent(mainPart);
			// 发送邮件    
			Transport.send(mailMessage);
			return true;
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return false;
	}

	public static void main(String[] argv) {
        sendHtmlMail("xpp@163.com", "title", "content", null);
	}
}
